package script;

import api.UserApi;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import utils.AssertUtil;
import utils.DBUtils;
import utils.ResponseData;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;

public class TestUser {
    private final UserApi userApi = new UserApi();
    private static final Logger logger = LoggerFactory.getLogger(TestUser.class);

    @BeforeMethod
    public void cleaData()  {
        String sql = "DELETE FROM mb_member_info WHERE member_id in (SELECT m.id from mb_member m  WHERE m.`name` = 'zzh01' or m.phone = '18033727699');";
        String sql2 = "DELETE FROM mb_member  WHERE `name` = 'zzh01' or phone = '18033727699';";
        DBUtils.execute(sql);
        DBUtils.execute(sql2);
    }
    @DataProvider
    public Object[][] buildData() throws Exception {

        String s = FileUtils.readFileToString(new File("./data/AddUser.json"), "UTF-8");
        JSONArray jsonArray = JSONObject.parseArray(s);
        Object[][] testData = new Object[jsonArray.size()][];
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            testData[i] = new Object[]{jsonObject.getString("name"),
                    jsonObject.getString("mobile"), jsonObject.getString("pwd"),
                    jsonObject.getString("rePwd"), jsonObject.getString("role"),
                    jsonObject.getIntValue("code"), jsonObject.getString("description")
                    , jsonObject.getIntValue("status")};
        }
        logger.info("testData={}", Arrays.deepToString(testData));
        return testData;

    }

    @Test(dataProvider = "buildData")
    public void addUser(String name, String mobile, String pwd, String rePwd, String role,int
                         code,String description,int status) throws Exception {
        ResponseData responseData = userApi.addUser(name, mobile, pwd, rePwd, role);
        //断言
        //断言{"description":"添加成功","status":200}
//        Assert.assertEquals(responseData.getStatusCode(), code);
//        Assert.assertEquals(responseData.getBody().getString("description"), description);
//        Assert.assertEquals(responseData.getBody().getIntValue("status"), status);
        AssertUtil.commonAssert(responseData,code,description,status);
    }

}
